      parameter (last_yr=2005)
      integer itmp(12),itmp0(12)
      integer mo(last_yr-1979,12),mo0(last_yr-1979,12)
C**** replace GHCN (unit 2) by USHCN (unit 1) data; new file: unit 12
      real dif(12)
C**** assumption is that IDs are ordered numerically low->high in both
C****               input files
      
      open(1,file='USHCN.v2.mean_noFIL',form='formatted')
      open(2,file='ghcn_us_end',form='formatted')
      open(10,file='ushcn-ghcn_offset_noFIL',form='formatted')

!                                       CountryCode,ID,year,T-data
   10 read(1,'(i3,i9,i4,12i5)',end=100) icc0,id0,iyr0,itmp0 ! read USHCN
      if(iyr0.lt.1980.or.iyr0.gt.last_yr) go to 10
   20 read(2,'(i3,i9,i4,12i5)',end=200) icc,id,iyr,itmp     ! read GHCN
      if(id.lt.id0.or.iyr.lt.iyr0.or.iyr.gt.last_yr) go to 20
      if(id.ne.id0.or.iyr.lt.iyr0) stop 'should not happen'
      if (iyr.gt.iyr0) then
   21   read(1,'(i3,i9,i4,12i5)',end=100) icc0,id0,iyr0,itmp0
        if(id.ne.id0.or.iyr.lt.iyr0) stop 'should not happen'
        if(iyr.gt.iyr0) go to 21
      end if
      do m=1,12
      do n=1,last_yr-1979
      mo0(n,m)=-9999
      mo (n,m)=-9999
      end do
      end do
C**** get 26 yrs of USHCN data
   25 if(iyr0.gt.last_yr.or.id0.ne.id) go to 30
      do m=1,12
        mo0(iyr0-1979,m) = itmp0(m)
      end do
      read(1,'(i3,i9,i4,12i5)',end=30) icc0,id0,iyr0,itmp0
      go to 25
C**** got 26 yrs of USHCN - now get GHCN-data
   30 id0=id
   31 if(iyr.gt.last_yr.or.id0.ne.id) go to 40
      do m=1,12
        mo(iyr-1979,m) = itmp(m)
      end do
      read(2,'(i3,i9,i4,12i5)',end=100) icc,id,iyr,itmp ! read GHCN
      go to 31
C**** compare data
   40 id=id0
      do m=1,12
        nok=0 ; di=0
        do n=last_yr-1979,1,-1
          if(mo0(n,m).gt.-9000.and.mo(n,m).gt.-9000) then
            nok=nok+1
            di=di+(mo0(n,m)-mo(n,m))
          end if
          if(nok.eq.10) go to 50
        end do
   50   dif(m)=di/nok
        if(nok.lt.1) dif(m)=-9999
      end do
      write(10,'(i10,12f7.0)') id,dif
      backspace (1)
      backspace (2)
      go to 10
c**** No more USHCN data - copy data for remaining non-USHCN stations
  100 write(*,*) 'done with ushcn'
  200 stop
      end
